package com.atguigu.realtime.app;

import com.atguigu.realtime.util.FlinkSourceUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/7/16 9:50
 */
public abstract class BaseAppV2 {
    
    protected abstract void handle(StreamExecutionEnvironment env,
                                   Map<String, DataStreamSource<String>> topicAndStreamMap);
    
    public void init(int port, int p, String groupIdAndCkPath, String... topics) {
        if (topics.length == 0) {
            throw new RuntimeException("传入的topic的个数必须大于等于1, 你现在传入的是0个topic");
        }
        
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);  // 端口的配置, 只在本地运行的时候有效
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(p);  // 并行度的设置: source 一般要和kafka的topic的分区数保持一致
        
        // 开启checkpoint
        env.enableCheckpointing(5000);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/gmall/" + groupIdAndCkPath);
        
        env.getCheckpointConfig().setCheckpointTimeout(30000);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
    
        Map<String, DataStreamSource<String>> topicAndStreamMap = new HashMap<>();
    
        for (String topic : topics) {
            DataStreamSource<String> stream = env.addSource(FlinkSourceUtil.getKafkaSource(groupIdAndCkPath, topic));
            topicAndStreamMap.put(topic, stream);
        }
        
        // 具体处理业务
        handle(env, topicAndStreamMap);
        
        
        try {
            env.execute(groupIdAndCkPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
